package com.nami.conver.controller.middleware.mq.consumer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.protobuf.InvalidProtocolBufferException;
import com.nami.conver.facade.pmsg.PrivateConverFacade;
import com.nami.conver.facade.pmsg.request.PrivateConverCmd;
import com.nami.gate.external.basic.constants.ConverTopicConst;
import com.nami.im.network.model.message.v2.Message;
import com.nami.transport.proto.codec.ImMessages;
import com.nami.transport.proto.codec.MqTransMsg;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = ConverTopicConst.PCHAT_UPD_CONVERS_TOPIC,
    consumerGroup = ConverTopicConst.PCHAT_UPD_CONVERS_CONSUMER_GROUP,
    consumeMode = ConsumeMode.CONCURRENTLY)
public class PrivateConverConsumer implements RocketMQListener<MessageExt> {

    private final PrivateConverFacade privateConverFacade;

    @Override
    public void onMessage(MessageExt msg) {
        try {
            TimeInterval timer = DateUtil.timer();
            PrivateConverCmd cmd = parsePChatConverCmd(msg.getBody());
            privateConverFacade.execute(cmd);
            if (timer.interval() > 200) {
                log.warn("[pconver] 单聊刷新会话超时，senderId={}, recvId={}, msgId={}", JSONUtil.toJsonStr(cmd));
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }

    private PrivateConverCmd parsePChatConverCmd(byte[] msg) {

        try {
            MqTransMsg.Logic2DispatchBody request = MqTransMsg.Logic2DispatchBody.parseFrom(msg);

            Message downMsg = JsonUtils.parseObject(request.getMessage().toByteArray(), Message.class);

            PrivateConverCmd cmd = new PrivateConverCmd();
            cmd.setSeq(downMsg.getMsgSeqNo());
            cmd.setTime(downMsg.getMsgTime());
            cmd.setPayload(downMsg.getMsgContent());
            cmd.setSenderId(downMsg.getSenderId());
            cmd.setReceiverId(downMsg.getTargetId());
            cmd.setAppKey(request.getSender().getAppKey());
            cmd.setMessageId(downMsg.getMsgId());

            return cmd;
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException(e);
        }


    }

}
